import { useState, useEffect, useCallback } from 'react';

interface Parameter {
  id: number;
  device_id: string;
  parameter_name: string;
  parameter_value: string;
  data_type?: string;
  measurement_unit?: string;
  is_required?: boolean;
  created_at?: string;
  updated_at?: string;
}

interface UseSqliteParametersResult {
  parameters: Parameter[];
  loading: boolean;
  error: string | null;
  updateParameter: (parameterId: number, value: string) => Promise<boolean>;
  saveParameters: (deviceId: string, parameterType: string, parameters: Partial<Parameter>[]) => Promise<boolean>;
  refetch: () => void;
}

export function useSqliteParameters(
  deviceId: string | null, 
  parameterType: 'naming' | 'position' | 'base' | null
): UseSqliteParametersResult {
  const [parameters, setParameters] = useState<Parameter[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchParameters = useCallback(async () => {
    if (!deviceId || !parameterType) {
      setParameters([]);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      
      const response = await fetch(`/api/sqlite-parameters?deviceId=${deviceId}&type=${parameterType}`);
      if (!response.ok) {
        throw new Error('获取参数失败');
      }
      
      const data = await response.json();
      setParameters(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setLoading(false);
    }
  }, [deviceId, parameterType]);

  useEffect(() => {
    fetchParameters();
  }, [fetchParameters]);

  const updateParameter = async (parameterId: number, value: string): Promise<boolean> => {
    try {
      setError(null);
      
      const response = await fetch('/api/sqlite-parameters', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          parameterType,
          parameterId,
          parameterValue: value
        }),
      });

      if (!response.ok) {
        throw new Error('更新参数失败');
      }

      // 更新本地状态
      setParameters(prev => prev.map(param => 
        param.id === parameterId 
          ? { ...param, parameter_value: value }
          : param
      ));

      return true;
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
      return false;
    }
  };

  const saveParameters = async (
    deviceId: string, 
    parameterType: string, 
    parameters: Partial<Parameter>[]
  ): Promise<boolean> => {
    try {
      setError(null);
      
      const response = await fetch('/api/sqlite-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          parameterType,
          parameters
        }),
      });

      if (!response.ok) {
        throw new Error('保存参数失败');
      }

      // 重新获取数据
      await fetchParameters();
      return true;
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
      return false;
    }
  };

  return {
    parameters,
    loading,
    error,
    updateParameter,
    saveParameters,
    refetch: fetchParameters,
  };
} 